
import { handleActions as createReducer } from "redux-actions" 
import { load_todo_success, add_todo_success, remove_todo_success, modify_todo_success, modify_todo_filter,
clear_todo_completed_success, edit_todo_success, modify_todo_name_success } from '../actions/todo.actions'
import { fromJS, setIn, mergeDeep, removeIn, getIn, updateIn } from "immutable"


const initState = fromJS({
  todos: [],
  filter: 'all'
})

const load_todo_action = (newState, action) => {
  return setIn(newState, ['todos'], action.payload)
}
const add_todo_action= (newState, action) => {
  return mergeDeep(newState, { todos: [action.payload] })
}
const remove_todo_action = (newState, action) => {
  let id = action.payload
  // 取出与id相同的下标的todo的位置
  let index = getIn(newState, ['todos']).findIndex(todo => todo.id === id)
  return removeIn(newState, ['todos', index])
}
const modify_todo_action = (newState, action) => {
  console.log(action)
  let index = getIn(newState, ['todos']).findIndex(todo => todo.id === action.payload.id)
  return updateIn(newState, ['todos', index],() => action.payload)
}
const modify_todo_filter_action = (newState, action) => {
  // console.log(action)  {type: 'modify_todo_filter', payload: 'active'}
  return setIn(newState,['filter'], action.payload)
}
const clear_todo_completed_action = (newState, action) => {
  let todos = getIn(newState,['todos']).filter(todo => !todo.isCompleted)
  return setIn(newState,['todos'], todos)
}
const edit_todo_action = (newState, action) => {
  // console.log(action)
  let index = getIn(newState, ['todos']).findIndex(todo => todo.id === action.payload.id)
  return updateIn(newState, ['todos', index],() => action.payload)
}
const modify_todo_name_action = (newState, action) => {
  // console.log(action)
  let index = getIn(newState, ['todos']).findIndex(todo => todo.id === action.payload.id)
  return updateIn(newState, ['todos', index],() => action.payload)
} 
const counterReducer = createReducer({
  [load_todo_success]: load_todo_action,
  [add_todo_success]: add_todo_action,
  [remove_todo_success]: remove_todo_action,
  [modify_todo_success]: modify_todo_action,
  [modify_todo_filter]: modify_todo_filter_action,
  [clear_todo_completed_success]: clear_todo_completed_action,
  [edit_todo_success]: edit_todo_action,
  [modify_todo_name_success]: modify_todo_name_action
},initState)


export default counterReducer